package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"pet-adopt-hub/models"

	"pet-adopt-hub/petrpc/internal/svc"
	"pet-adopt-hub/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *petrpc.AddRequest) (*petrpc.AddResponse, error) {
	// todo: add your logic here and delete this line
	tx := models.DB.Begin()
	style := models.Style{
		Model: gorm.Model{},
		Name:  in.StyleName,
	}
	err := tx.Where("name=?", in.StyleName).FirstOrCreate(&style).Error
	if err != nil {
		tx.Rollback()
		return nil, errors.New("品种信息添加失败")
	}
	person := models.Person{
		Model: gorm.Model{},
		Name:  in.PersonName,
	}
	err = tx.Where("name=?", in.PersonName).FirstOrCreate(&person).Error
	var pet models.Pet
	tx.Where("name=?", in.Name).Find(&pet)
	if pet.ID != 0 {
		tx.Rollback()
		return nil, errors.New("宠物名称不能重复，请重新输入")
	}
	pet = models.Pet{
		Model:    gorm.Model{},
		Name:     in.Name,
		Sex:      in.Sex,
		Context:  in.Context,
		StyleId:  int(style.ID),
		PersonId: int(person.ID),
	}
	tx.Debug().Create(&pet)
	tx.Commit()
	return &petrpc.AddResponse{
		PetId: int64(pet.ID),
	}, nil
}
